package cn.rkylin.oms.system.shop.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.base.AbstractAdapterFactory;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;

/**
 * 店铺控制器
 *
 * @author wangxiaoyi
 * @version 1.0
 * @created 13-1月-2017 09:11:15
 */
@Controller
@RequestMapping("/shop")
public class ShopController extends ApolloController {
    private static final Log logger = LogFactory.getLog(ShopController.class);
    
    @Value("${oms.address}")
    private String omsAddress;
    
    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;
    
    /**
     * 自动下载指定店铺的订单
     * 
     * @param shopId
     *            指定的店铺
     * 
     * @return map
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
    public Map<String, Object> refreshToken(String shopId) throws Exception {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        ShopVO shop = AbstractAdapterFactory.getShop(shopId);
        if (shop == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "店铺不存在");
            return returnMap;
        } else if (StringUtils.isBlank(shop.getAppKey()) || StringUtils.isBlank(shop.getAppSecret())) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "店铺参数配置未设置");
            return returnMap;
        } else if (StringUtils.isBlank(shop.getAppSecret()) || StringUtils.isBlank(shop.getRefreshToken())) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "店铺未授权");
            return returnMap;
        }
        // 淘宝店铺token更新(目前只有一种，其它方式不确定，以后对接其它平台再重构到具体的模式)
        // 详见：http://open.taobao.com/docs/doc.htm?spm=a219a.7629140.0.0.rWFFKn&treeId=1&articleId=102635&docType=1&qq-pf-to=pcqq.c2c
        String url = "https://oauth.taobao.com/token";
        //String url = "https://oauth.tbsandbox.com/token";
        
        StringBuilder props = new StringBuilder();
        String refreshToken = shop.getRefreshToken();
        String clientId = shop.getAppKey();
        String clientSecret = shop.getAppSecret();
        props.append("grant_type=refresh_token");
        props.append("&refresh_token=" + refreshToken);
        props.append("&client_id=" + clientId);
        props.append("&client_secret=" + clientSecret);
        String strTOPResult = "";
        try {
            strTOPResult = HttpUtils.sendByPost(url, props.toString());
            logger.debug(strTOPResult);
            JSONObject resultJSON = JSONObject.parseObject(strTOPResult);
            String newRefreshToken = resultJSON.getString("refresh_token");
            // 新token和旧token不一致才更新
            if (StringUtils.isNotBlank(newRefreshToken)) {
                ShopVO shopVO = new ShopVO();
                shopVO.setShopId(shopId);
                shopVO.setRefreshToken(newRefreshToken);
                shopService.update(shopVO);
                returnMap.put("success", "true");
            } else {
                logger.debug("淘宝刷新店铺token失败，店铺id:" + shopId);
                returnMap.put("result", "淘宝刷新店铺token失败，店铺id:" + shopId);
                returnMap.put("success", "false");
            }
        } catch (IOException e) {
            logger.debug(e.getMessage());
            returnMap.put("result", e.getMessage());
            returnMap.put("success", "false");
            e.printStackTrace();
        }
        return returnMap;
    }
}
